def search_rotated(nums, target):
    """
    问题：在旋转后的有序数组中查找目标（如[4,5,6,7,0,1,2]）
    思路：二分查找，先判断左右半区哪部分有序，再缩小范围
    """
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid

        # 左半区有序（nums[left] <= nums[mid]）
        if nums[left] <= nums[mid]:
            # 目标在左半区
            if nums[left] <= target < nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        # 右半区有序
        else:
            # 目标在右半区
            if nums[mid] < target <= nums[right]:
                left = mid + 1
            else:
                right = mid - 1
    return -1


# 测试
print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0))  # 输出：4
print(search_rotated([4, 5, 6, 7, 0, 1, 2], 3))  # 输出：-1